/*
 * NetRayt
 * Copyright (c) 2007-2008 Maciej Nabozny.
 *
 * NetRayt is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * NetRayt is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with NetRayt; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#include "server.h"
#include "connFunc.h"

/*******************************************/
/*             Klasa serwera               */
/*******************************************/

server::server(QWidget *parent, Qt::WFlags f): QMainWindow(parent, f) {
	ui.setupUi(this);
	QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
	
	srv = NULL;
	connect(ui.startServer, SIGNAL(clicked()), this, SLOT(startServer()));
}

/*
 * Uruchom nowy serwer
 * Wywoływane po kliknięciu guziczka
 */
void server::startServer() {
	port = ui.port->text().toInt();
	
	if (srv != NULL) {
		delete srv;
	}
	
	qDebug("Uruchamiam serwer");
	srv = new QTcpServer();
	srv->listen(QHostAddress::Any, port);
	
	ui.serverStatus->setText(QString("Serwer działa"));
	
	connect(srv, SIGNAL(newConnection()), this, SLOT(startThread()));
}

void server::startThread() {
	QTcpSocket *conn = srv->nextPendingConnection();
	
	connFunc *sf = new connFunc();
	connThread *t=new connThread(conn);
	
	
	// Ustaw parametry komputera:
	sf->cpucV = QString("%1").arg(ui.cpucV->value());
	sf->cpufV = ui.cpufV->text();
	sf->memV = ui.memV->text();
	if (sf->memV == "" || sf->cpufV == "") {
		qDebug("Podaj parametry serwera!");
		return;
	}
	
	QListWidgetItem *clientInfo = new QListWidgetItem(conn->localAddress().toString());
	ui.clientList->insertItem(0, clientInfo);
	
	connect(t, SIGNAL(recRequest(argList, QString)), sf, SLOT(getRequest(argList, QString)));
	connect(sf, SIGNAL(sendResponse(argList, QString)), t, SLOT(sendResponse(argList, QString)));
	
	t->start();
}

